package com.l024.easysecurity.common.utils;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 */
public class GuavaCacheUtil {
    private static GuavaCacheUtil guavaCacheUtil;
    public static Cache<String,String> guavaCache;
    private final static Logger logger = LoggerFactory.getLogger(GuavaCacheUtil. class);

    public static GuavaCacheUtil getInstance(){
        if(guavaCacheUtil==null){
            synchronized (GuavaCacheUtil.class){
                if(guavaCacheUtil==null){
                    guavaCacheUtil = new GuavaCacheUtil();
                }
            }
        }
        return guavaCacheUtil;
    }

    private GuavaCacheUtil(){
        guavaCache= CacheBuilder.newBuilder().maximumSize(100)
                .expireAfterAccess(15, TimeUnit.MINUTES)
                .removalListener(new RemovalListener<String, String>() {
                    @Override
                    public void onRemoval(RemovalNotification<String,String> notification) {
                        //移除缓存监听
                        logger.info("guava移除监听:"+notification.getValue());
                    }
                }).build();
    }

    public Cache<String,String> getCache(){
        return guavaCache;
    }
}
